<template>
  <div id="search">
    <title-bar>
      <h2 slot="left" @click="goback">
        <van-icon name="arrow-left"></van-icon>
      </h2>   
      <h2 slot="center">搜索</h2>
    </title-bar>

    <search-bar 
    @historyChange="getData"
    @getSearchList="getList"
    ></search-bar>  
    <search-title @priceSort="sortPrice"></search-title>
    <search-goods 
    :goodsList="searchList"
    @getGoodsId="getId"></search-goods>


  </div>
</template>

<script>
import Vue from 'vue';
import { Icon } from 'vant';
import 'vant/lib/icon/style'
Vue.use(Icon);

import SearchBar from '../components/SearchChildrenComponents/SearchBar.vue';
import TitleBar from '../components/common/title_bar/TitleBar.vue'
import SearchTitle from '../components/SearchChildrenComponents/SearchTitle.vue';
import SearchGoods from '../components/SearchChildrenComponents/SearchGoods.vue';


export default {
  components: { TitleBar, SearchBar, SearchTitle, SearchGoods },
  name:"Search",
  props:{
    itemName:String
  },
  data() {
    return {
      historyList:[],
      searchList:[],
    }
  },
  methods:{
    goback(){
      this.$emit("gohome")
    },
    getData(v){
      this.historyList.push(v)
      this.historyList = [...new Set(this.historyList)]
    },
    getList(d){
      this.searchList = d
      console.log(this.searchList)
    },
    sortPrice(boo){
      if(boo){
        this.searchList = this.searchList.sort(function(a,b){
          return a.goods_price - b.goods_price
        })
      }else{
        this.searchList = this.searchList.sort(function(a,b){
          return b.goods_price - a.goods_price
        })
      }
    },
    getId(id){
      this.$emit("getId",id)
    }
  },
  created() {
    var arr = localStorage.getItem('historyData');
    if(arr == null){
      localStorage.setItem('historyData',JSON.stringify([]))
    }else{
      this.historyList = JSON.parse(arr);
    }

    if(this.itemName != ""){
      this.$http({
        url:"/api/public/v1/goods/search",
        methods:"get",
        params:{
          query:this.itemName
        }
      }).then(res => {
       this.searchList =  res.data.message.goods
      })
    }
  },
}
</script>

<style scoped>

</style>
